function setStorage(key, value) {
	if (!value || value == undefined || value == null) {
		value = ""
	}
  window.localStorage.setItem(key, value)
}
function getStorage(key, defaultValue) {
	try {
		var value = window.localStorage.getItem(key);
		if (value == undefined || value == null) {
			return defaultValue || ""
		}
		if (value) {
			return value
		}
		return defaultValue || ""
	} catch (e) {
		return defaultValue || ""
	}
}
function getStorageJson(key) {
  var keyStr = getStorage(key)
  if(!keyStr || keyStr === '') {
    return null
  }
  return JSON.parse(keyStr)
}

function isInPolygon(x, y, points) {
  var counter = 0;
  var xinters = 0;
  var p1 = null;
  var p2 = null;
  var pointCount = points.length;
  p1 = points[0];
  for (var i = 1; i <= pointCount; i++) {
    p2 = points[i % pointCount];
    if (x > Math.min(p1.x, p2.x) && x <= Math.max(p1.x, p2.x)) {
      if (y <= Math.max(p1.y, p2.y)) {
        if (p1.x != p2.x) {
          xinters = (x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;
          if (p1.y == p2.y || y <= xinters) {
            counter++;
          }
        }
      }
    }
    p1 = p2;
  }
  if (counter % 2 == 0) {
    return false;
  } else {
    return true;
  }
}

function getDefaultFloorId(floors, activeBuilding) {
  var floorId = ""
  for (var i = 0; i < floors.length; i++) {
    if (floors[i].buildingName === activeBuilding) {
      floorId = floors[i].id
      if (floors[i].floorName === "L1" || floors[i].floorName === "1L" || floors[i].floorName === "F1" || floors[i]
        .floorName === "1F") {
        return floorId;
      }
    }
  }
  return floorId;
}
/**
 * @param {Object} detail
 * @param {Object} callback
 * 目前返回的类型有 merchant、park、utilitie、user、unknown
 */
function checkClickType(detail, callback) {
  var floorId = detail.floorId
  if (!floorId) {
    return
  }
  var object = detail.sprite || detail.object
  if (!object) {
    if (detail.hasOwnProperty('floorId')) {
      callback && callback("未命名区域", 'unknown', {
        x: detail.position.x,
        y: detail.position.y,
        floorId: detail.floorId
      })
    }
    return
  }
  var objType = object.objType
  var dataType = object.dataType
  if (objType === "merchant" && dataType === "merchant") {
    callback && callback(object.userData.name, 'merchant', object.userData)
  } else if (objType === "merchant" && dataType === "park") {
    callback && callback(object.userData.name, 'park', object.userData)
  } else if (objType === "utilitie" && dataType === "utilitie") {
    callback && callback(object.userData.utilitiesName, 'utilitie', object.userData)
  } else if (objType === "poi" && dataType === "merchant") {
    callback && callback(object.userData.name, 'merchant', object.userData)
  } else if (objType === "poi" && dataType === "utilitie") {
    callback && callback(object.userData.utilitiesName, 'utilitie', object.userData)
  } else if (objType === "poi" && dataType === "park") {
    callback && callback(object.userData.name, 'park', object.userData)
  } else if (objType === "poi" && dataType === "user") {
    callback && callback(object.objId, 'user', object.userData)
  } else {
    callback && callback("未命名区域", 'unknown', {
      x: detail.position.x,
      y: detail.position.y,
      floorId: floorId
    })
  }
}

function getItemById(list, id) {
  for (var i = 0; i < list.length; i++) {
    if (list[i].id === id) {
      return list[i]
    }
  }
  return null
}

function getParkSpaceBySpace(parkSpaceList, spaceCode, buildingName) {
  for (var i = 0; i < parkSpaceList.length; i++) {
    var space = parkSpaceList[i]
    var children = space.children
    for (var j = 0; j < children.length; j++) {
      var code = children[j]
      if (space.buildingName === buildingName && code === spaceCode) {
        return space
      }
    }
  }
  return null
}

function getPlaceList(makerGroupList, makerList) {
  var groupId = ""
  for (var i = 0; i < makerGroupList.length; i++) {
    if (makerGroupList[i].type === "hotplace") {
      groupId = makerGroupList[i].id;
      break;
    }
  }
  return makerList.filter((maker) => {
    return maker.groupId === groupId
  })
}

function distance(point1, point2) {
  return Math.sqrt((point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y - point2.y));
}
function distanceSqrt(point1, point2) {
  return (point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y - point2.y);
}

function getRecentPosition(location, merchants, parkSpaceList, makerList) {
  var minDis = 10000 * 10000
  var near = {}

  for (var i = 0; i < merchants.length; i++) {
    if (location.floorId === merchants[i].floorId) {
      var dis = distanceSqrt(location, merchants[i])
      if (dis < minDis) {
        minDis = dis
        near.type = 'merchant',
          near.object = merchants[i]
      }
    }
  }
  for (var i = 0; i < parkSpaceList.length; i++) {
    if (location.floorId === parkSpaceList[i].floorId) {
      var dis = distanceSqrt(location, parkSpaceList[i])
      if (dis < minDis) {
        minDis = dis
        near.type = 'park',
          near.object = parkSpaceList[i]
      }
    }
  }
  for (var i = 0; i < makerList.length; i++) {
    if (location.floorId === makerList[i].floorId) {
      var dis = distanceSqrt(location, makerList[i])
      if (dis < minDis) {
        minDis = dis
        near.type = 'maker',
          near.object = makerList[i]
      }
    }
  }
  near.minDis = minDis
  return near
}

/**
 * 深度拷贝目标点
 */
function getCopyObject(object) {
  return {
    name: object.name,
    type: object.type,
    object: {
      floorId: object.object.floorId,
      x: object.object.x,
      y: object.object.y
    }
  }
}

function getFaceImg(bgUrl, faceUrl, callback) {
  var canvas = document.createElement('canvas');
  var context = canvas.getContext('2d');
  canvas.width = 256;
  canvas.height = 256;
  var imgBg = new Image();
  imgBg.src = bgUrl;
  imgBg.setAttribute('crossOrigin', 'anonymous');
  imgBg.onload = function() {
    context.drawImage(imgBg, 0, 0, 256, 256);
    var imgFace = new Image();
    imgFace.src = faceUrl
    imgFace.setAttribute('crossOrigin', 'anonymous');
    imgFace.onload = function() {
      var radius = 92
      var startX = 36
      var startY = 32
      context.save()
      context.beginPath()
      context.arc(startX + radius, startY + radius, radius, 0, Math.PI * 2, false)
      context.clip()
      context.drawImage(imgFace, 0, 0, imgFace.width, imgFace.height, startX, startY, 2 * radius, 2 * radius)
      var baseStr = canvas.toDataURL("image/png");
      callback && callback(baseStr)
    }
    imgFace.onerror = function() {
      callback && callback(bgUrl)
    }
  };
  imgBg.onerror = function() {
    callback && callback(bgUrl)
  }
}
function getRandom(min, max) {
	return Math.floor(Math.random()*max+min)
};

function getNameImg(bgUrl, name, callback) {
	var canvas = document.createElement('canvas');
	var context = canvas.getContext('2d');
	canvas.width = 256;
	canvas.height = 256;
	var imgBg = new Image();
	imgBg.src = bgUrl;
	imgBg.setAttribute('crossOrigin', 'anonymous');
	imgBg.onload = function() {
		context.drawImage(imgBg, 0, 0, 256, 256);
		var font = "54px 'Microsoft Yahei'";
		context.font = font;
		context.textBaseline = "top";
		var textwidth = context.measureText(name).width;
		context.font = font;
		context.fillStyle = "#333333";
		context.fillText(name, (256-textwidth)*0.5, 66);
		context.fillText(name, (256-textwidth)*0.5, 66);
		context.fillText(name, (256-textwidth)*0.5, 66);
		var baseStr = canvas.toDataURL("image/png");
		callback && callback(baseStr)
	};
	imgBg.onerror =function () {
		callback && callback(bgUrl)
	}
}
export {
  setStorage,
  getStorage,
  getStorageJson,
  getDefaultFloorId,
  checkClickType,
  getItemById,
  getParkSpaceBySpace,
  getPlaceList,
  getRecentPosition,
  getCopyObject,
  getFaceImg,
  isInPolygon,
  getNameImg,
  getRandom,
  distance
}
